using System.Collections.ObjectModel;
using FileTransferDesktop.Services;
using FileTransferDesktop.Views.Dialogs;
using FileTransferDesktop.Views.Windows;
using Microsoft.Extensions.DependencyInjection;
using Wpf.Ui;
using Wpf.Ui.Controls;
using AuthDialogViewModel = FileTransferDesktop.ViewModels.Dialogs.AuthDialogViewModel;
using WpfApplication = System.Windows.Application;

namespace FileTransferDesktop.ViewModels.Windows;

public partial class MainWindowViewModel : ObservableObject
{
    private readonly IAuthenticationService _authenticationService;
    private readonly ISnackbarService _snackbarService;
    private readonly ITrayService _trayService;

    [ObservableProperty]
    private string _applicationTitle = "FileTransfer";

    [ObservableProperty]
    private bool _isLoggedIn = false;

    [ObservableProperty]
    private string _currentUserName = string.Empty;

    [ObservableProperty]
    private string _avatarUrl = "/Assets/avatar.png";

    [ObservableProperty]
    private bool _isDialogOpen = false;

    [ObservableProperty]
    private ObservableCollection<object> _menuItems =
    [
        new NavigationViewItem()
        {
            Content = "主页",
            Icon = new SymbolIcon { Symbol = SymbolRegular.Home24 },
            TargetPageType = typeof(Views.Pages.DashboardPage),
        },
        new NavigationViewItem()
        {
            Content = "上传",
            Icon = new SymbolIcon { Symbol = SymbolRegular.CloudArrowUp20 },
            TargetPageType = typeof(Views.Pages.UploadPage),
        },
        new NavigationViewItem()
        {
            Content = "下载",
            Icon = new SymbolIcon { Symbol = SymbolRegular.CloudArrowDown20 },
            TargetPageType = typeof(Views.Pages.DownloadPage),
        },
        new NavigationViewItem()
        {
            Content = "管理",
            Icon = new SymbolIcon { Symbol = SymbolRegular.FolderOpen24 },
            TargetPageType = typeof(Views.Pages.ManagementPage),
        },
        new NavigationViewItem()
        {
            Content = "WinForms 示例",
            Icon = new SymbolIcon { Symbol = SymbolRegular.WindowApps24 },
            TargetPageType = typeof(Views.Pages.WinFormsIntegrationPage),
        },
    ];

    [ObservableProperty]
    private ObservableCollection<object> _footerMenuItems = new();

    public MainWindowViewModel(
        IAuthenticationService authenticationService,
        ISnackbarService snackbarService,
        ITrayService trayService
    )
    {
        _authenticationService = authenticationService;
        _snackbarService = snackbarService;
        _trayService = trayService;
        _authenticationService.AuthenticationStatusChanged += OnAuthenticationStatusChanged;

        InitializeFooterMenuItems();
        InitializeTray();

        // 尝试恢复登录状态
        _ = Task.Run(async () => await _authenticationService.RestoreAuthenticationAsync());
    }

    private void InitializeTray()
    {
        _trayService.Initialize();
        _trayService.Show();
        _trayService.UpdateTooltip(ApplicationTitle);
    }

    private void InitializeFooterMenuItems()
    {
        FooterMenuItems.Clear();

        // Settings navigation item
        FooterMenuItems.Add(
            new NavigationViewItem()
            {
                Content = "设置",
                Icon = new SymbolIcon { Symbol = SymbolRegular.Settings24 },
                TargetPageType = typeof(Views.Pages.SettingsPage),
            }
        );

        // About navigation item
        FooterMenuItems.Add(
            new NavigationViewItem()
            {
                Content = "关于",
                Icon = new SymbolIcon { Symbol = SymbolRegular.Info24 },
                TargetPageType = typeof(Views.Pages.AboutPage),
            }
        );
    }

    private void OnAuthenticationStatusChanged(object? sender, bool isAuthenticated)
    {
        IsLoggedIn = isAuthenticated;
        if (isAuthenticated)
        {
            CurrentUserName = _authenticationService.CurrentUser?.Username ?? "";

            // Update avatar URL - use user's avatar if available, otherwise default
            var currentUser = _authenticationService.CurrentUser;
            AvatarUrl = !string.IsNullOrEmpty(currentUser?.AvatarUrl)
                ? currentUser.AvatarUrl
                : "/Assets/avatar.png";

            // 显示登录成功通知
            if (currentUser != null)
            {
                var successMessage =
                    $"登录成功！欢迎回来，{currentUser.DisplayName ?? currentUser.Username}"; // 使用UI线程显示Snackbar
                WpfApplication.Current.Dispatcher.Invoke(() =>
                {
                    _snackbarService.Show(
                        "登录成功",
                        successMessage,
                        ControlAppearance.Success,
                        new SymbolIcon(SymbolRegular.CheckmarkCircle24),
                        TimeSpan.FromSeconds(4)
                    );
                });
            }
        }
        else
        {
            CurrentUserName = string.Empty;
            AvatarUrl = "/Assets/avatar.png"; // Reset to default avatar when logged out
        }
    }

    [ObservableProperty]
    private ObservableCollection<MenuItem> _trayMenuItems =
    [
        new MenuItem { Header = "Home", Tag = "tray_home" },
    ];

    [ObservableProperty]
    private string _userInitial = "H";

    [RelayCommand]
    private async Task LogoutAsync()
    {
        try
        {
            await _authenticationService.LogoutAsync();
        }
        catch (Exception ex)
        {
            var errorDialog = new Wpf.Ui.Controls.MessageBox
            {
                Title = "错误",
                Content = $"登出时发生错误：{ex.Message}",
            };
            await errorDialog.ShowDialogAsync();
        }
    }

    [RelayCommand]
    private async Task ShowLoginDialogAsync()
    {
        await ShowAuthDialogAsync(isRegisterMode: false);
    }

    [RelayCommand]
    private async Task ShowRegisterDialogAsync()
    {
        await ShowAuthDialogAsync(isRegisterMode: true);
    }

    private async Task ShowAuthDialogAsync(bool isRegisterMode)
    {
        try
        {
            // 设置对话框打开状态，禁用界面
            IsDialogOpen = true; // 创建对话框
            var dialogWindow = new DialogWindow() { Title = "用户认证" };
            var mainWindow = App.Services.GetService<MainWindow>()!;

            await ShowAuthDialogContent(dialogWindow, mainWindow, isRegisterMode);
        }
        catch (Exception ex)
        {
            // 错误处理
            var errorDialog = new Wpf.Ui.Controls.MessageBox
            {
                Title = "错误",
                Content = $"显示{(isRegisterMode ? "注册" : "登录")}对话框时发生错误：{ex.Message}",
            };
            await errorDialog.ShowDialogAsync();
        }
        finally
        {
            // 恢复界面状态
            IsDialogOpen = false;
        }
    }

    private Task ShowAuthDialogContent(
        DialogWindow dialogWindow,
        MainWindow mainWindow,
        bool isRegisterMode
    )
    {
        var authControl = App.Services.GetService<AuthDialogControl>()!;
        var authViewModel = App.Services.GetService<AuthDialogViewModel>()!;
        var authenticationService = App.Services.GetService<IAuthenticationService>()!;

        // 设置初始模式
        authViewModel.IsRegisterMode = isRegisterMode;

        authenticationService.AuthenticationStatusChanged += AuthSuccessHandler;

        try
        {
            dialogWindow.SetContent(authControl);
            dialogWindow.ShowDialog(mainWindow);
        }
        finally
        {
            authenticationService.AuthenticationStatusChanged -= AuthSuccessHandler;
        }

        return Task.CompletedTask;

        // 订阅认证成功事件
        void AuthSuccessHandler(object? sender, bool status)
        {
            if (!status)
                return;
            WpfApplication.Current.Dispatcher.Invoke(dialogWindow.Close);
        }
    }

    [ObservableProperty]
    private bool _isFlyoutOpen;

    [RelayCommand]
    private void ToggleFlyout()
    {
        IsFlyoutOpen = !IsFlyoutOpen;
    }
}
